package com.shqcjd.sinopecdemomobile.ui.fragment.mine;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.AppConstant;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.AllTaskBean;
import com.shqcjd.sinopecdemomobile.model.pojo.QRScanBean;
import com.shqcjd.sinopecdemomobile.model.pojo.TaskCodeBean;
import com.shqcjd.sinopecdemomobile.ui.activity.FileListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.GenerateQRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.InspectionTaskActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.WaitInspectionAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseFragment;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;
import com.shqcjd.sinopecdemomobile.util.SpacesItemDecoration;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;

import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 待巡检
 * Created by sy on 2019/3/22.
 */

public class WaitInspectionFrament extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener{
    private static final int PAGE_SIZE = 6;
    private int mNextRequestPage = 1;
    private static final int INSPECTION_TYPE = 1;//1待巡检  2已巡检

    @BindView(R.id.rv_inspection_list)
    RecyclerView rvInspectionList;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;


    private WaitInspectionAdapter waitInspectionAdapter;
    private View notDataView;

    public static WaitInspectionFrament newInstance() {
        return new WaitInspectionFrament();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_wait_inspection;
    }

    @Override
    public void initData() {
        refresh();
    }



    @Override
    public void initView(View rootView) {
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvInspectionList.getParent(), false);
        initInspectionList();
    }

    private void initInspectionList() {
        waitInspectionAdapter = new WaitInspectionAdapter();
        rvInspectionList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvInspectionList.addItemDecoration(new SpacesItemDecoration(UIUtils.dip2px(10), UIUtils.dip2px(9)));
        rvInspectionList.setAdapter(waitInspectionAdapter);
        swipeRefresh.setOnRefreshListener(this);
        waitInspectionAdapter.setOnLoadMoreListener(this,rvInspectionList);
        waitInspectionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AllTaskBean.ListBean item = (AllTaskBean.ListBean) adapter.getItem(position);
                Intent intent;
                switch (view.getId()) {
                    case R.id.tv_generate_qr://生成二维码
                        TaskCodeBean taskCodeBean = new TaskCodeBean();
                        taskCodeBean.user_id = item.user_id;
                        taskCodeBean.task_id = item.taskId;
                        QRScanBean bean = new QRScanBean();
                        Gson gson = new Gson();
                        bean.json = gson.toJson(taskCodeBean);
                        bean.sceneType =3;
                        bean.token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
                        String json = gson.toJson(bean);

                        intent = new Intent(getContext(), GenerateQRcodeActivity.class);
                        intent.putExtra("QRcode",json);
                        startActivity(intent);
                        break;
                    case R.id.tv_start_inspection://开始巡检
                        intent = new Intent(getContext(),InspectionTaskActivity.class);
                        intent.putExtra("taskId",item.taskId);
                        startActivity(intent);
                        break;
                    case R.id.tv_file_btn://文件列表
                        intent = new Intent(getContext(), FileListActivity.class);
                        intent.putExtra("taskId", item.taskId);
                        startActivity(intent);
                        break;
                }
            }
        });
    }


    private void refresh() {
        mNextRequestPage = 1;
        //这里的作用是防止下拉刷新的时候还可以上拉加载
        waitInspectionAdapter.setEnableLoadMore(false);
//        Map<String, Integer> map = new HashMap<>();
//        map.put("pageIndex",mNextRequestPage);
//        map.put("pageSize",PAGE_SIZE);
//        map.put("state",INSPECTION_TYPE);//1待巡检  2已巡检

        ApiService.getAllTaskList(mNextRequestPage,PAGE_SIZE,INSPECTION_TYPE)// INSPECTION_TYPE 1待完成  2已完成
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AllTaskBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<AllTaskBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        waitInspectionAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        waitInspectionAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }
                });
    }

    private void loadMore() {
//        Map<String, Integer> map = new HashMap<>();
//        map.put("pageIndex",mNextRequestPage);
//        map.put("pageSize",PAGE_SIZE);
//        map.put("state",INSPECTION_TYPE);//1待巡检  2已巡检

        ApiService.getAllTaskList(mNextRequestPage,PAGE_SIZE,INSPECTION_TYPE)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AllTaskBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<AllTaskBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        waitInspectionAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    public void showRefreshView(Boolean refresh) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refresh);
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                waitInspectionAdapter.setNewData(data);
            } else {
                waitInspectionAdapter.setNewData(null);
                waitInspectionAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                waitInspectionAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            waitInspectionAdapter.loadMoreEnd(isRefresh);
        } else {
            waitInspectionAdapter.loadMoreComplete();
        }
    }


}
